#include <iostream>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>
#include <thread>
#include "Threadqueue.hpp"

// 服务器类
class Server {
public:
    Server(int port, ThreadSafeQueue<std::string>& receiveQueue, ThreadSafeQueue<std::string>& sendQueue)
        : port_(port), server_sockfd_(-1), receiveQueue_(receiveQueue), sendQueue_(sendQueue) {}

    // 启动服务器
    bool start() {
        server_sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (server_sockfd_ < 0) {
            std::cerr << "Failed to create socket" << std::endl;
            return false;
        }

        struct sockaddr_in server_addr;
        memset(&server_addr, 0, sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.s_addr = INADDR_ANY;
        server_addr.sin_port = htons(port_);

        if (bind(server_sockfd_, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
            std::cerr << "Bind failed" << std::endl;
            close(server_sockfd_);
            return false;
        }

        if (listen(server_sockfd_, 5) < 0) {
            std::cerr << "Listen failed" << std::endl;
            close(server_sockfd_);
            return false;
        }

        std::cout << "Server listening on port " << port_ << std::endl;
        return true;
    }

    // 处理客户端连接
    void acceptConnections() {
        while (true) {
            struct sockaddr_in client_addr;
            socklen_t addrlen = sizeof(client_addr);
            int client_sock = accept(server_sockfd_, (struct sockaddr*)&client_addr, &addrlen);
            if (client_sock < 0) {
                std::cerr << "Failed to accept client connection" << std::endl;
                continue;
            }

            std::cout << "Client connected" << std::endl;
            std::thread(&Server::handleClient, this, client_sock).detach();
        }
    }

    // 处理客户端通信
    void handleClient(int client_sock) {
        std::thread receive_thread(&Server::receiveData, this, client_sock);  // 处理接收数据
        std::thread send_thread(&Server::sendData, this, client_sock);        // 处理发送数据

        receive_thread.join();
        send_thread.join();
    }

private:
    // 从客户端接收数据并存入队列
    void receiveData(int client_sock) {
        char buffer[1024];
        while (true) {
            memset(buffer, 0, sizeof(buffer));
            int bytes_received = recv(client_sock, buffer, sizeof(buffer), 0);
            if (bytes_received <= 0) {
                std::cerr << "Client disconnected or error" << std::endl;
                close(client_sock);
                break;
            }

            std::string data_received = std::string(buffer);
            receiveQueue_.push(data_received);  // 将接收到的数据存入队列
            std::cout << "Received from client: " << data_received << std::endl;
        }
    }

    // 从队列中获取数据并发送给客户端
    void sendData(int client_sock) {
        while (true) {
            // 从发送队列中取数据并发送
            std::string data_to_send = sendQueue_.pop();
            if (send(client_sock, data_to_send.c_str(), data_to_send.size(), 0) <= 0) {
                std::cerr << "Error sending data to client" << std::endl;
                close(client_sock);
                break;
            }

            std::cout << "Sent to client: " << data_to_send << std::endl;
        }
    }

private:
    int port_;
    int server_sockfd_;
    ThreadSafeQueue<std::string>& receiveQueue_;  // 接收数据队列
    ThreadSafeQueue<std::string>& sendQueue_;     // 发送数据队列
};